<template>
  <div class="app-container calendar-list-container" v-loading="loading">
    <el-row>
      <el-col class="col-bottom">
        <h3>基础设置</h3>
      </el-col>
      <el-col class="col-top">
        <el-form ref="form1" :model="form" :inline="true" label-width="90px">
          <el-form-item label="活动标题" prop="active_title" :rules="filter_rules({required:true})">
            <el-input clearable style="width: 250px;" placeholder="请输入活动名称" v-model.trim="form.active_title" >
            </el-input>
          </el-form-item>
          <el-form-item label="抽奖时间" prop="date" :rules="filter_rules({required:true})">
            <el-date-picker v-model="form.date" type="daterange" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <el-form ref="form2" :model="form" :inline="true" label-width="90px">
          <el-form-item label="描述" prop="active_desc" :rules="filter_rules({required:true})">
            <textarea cols="95" rows="5" style="padding: 10px; border-radius: 5px;" placeholder="请输入详细描述..." v-model.trim="form.active_desc"></textarea>
          </el-form-item>
        </el-form>
        <el-form ref="form3" :model="form" label-width="90px">
          <el-form-item label="活动封面" prop="file_path" :rules="filter_rules({type: 'upload'})">
            <!-- <el-upload class="avatar-uploader" action="/api/backstage/fileUpload" name="file_path" :show-file-list="false" 
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="form.file_path" :src="form.file_path" width="100%" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload> -->
            <img v-if="form.file_path" :src="form.file_path" class="avatar" @click="sizeSet">
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="sizeSet"></i>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col class="col-bottom">
        <h3>奖项设置</h3>
      </el-col>
      <el-col :class="{'col-temp': num != 8}" v-for="num in 8" :key="num">
        <rowTemp ref="childValidate" :title="'宫格' + tempNames[num - 1]" :num="num - 1" @judge="judge" ></rowTemp>
      </el-col>
    </el-row>
    <el-row>
      <el-col class="col-bottom col-top">
        <h3>功能设置</h3>
      </el-col>
      <el-col class="col-top">
        <el-row>
          <el-form ref="form4" :model="form" :inline="true">
            <el-col :span="3">
              <el-form-item label="每人总抽奖机会">
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item>
                  <el-switch v-model="form.everyone" inactive-text="关闭" active-text="开启">
                  </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item prop="opportunity_everyone" :rules="filter_rules({required: form.everyone|| false, type: 'integer'})">
                  <el-input clearable placeholder="限制的数量" v-model.number="form.opportunity_everyone">
                  </el-input>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
        <el-row>
          <el-form ref="form5" :model="form" :inline="true">
            <el-col :span="3">
              <el-form-item label="每人每日抽奖机会">
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item>
                  <el-switch v-model="form.everyday" inactive-text="关闭" active-text="开启">
                  </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item prop="opportunity_everyday" :rules="filter_rules({required: form.everyday|| false, type: 'integer'})">
                  <el-input clearable placeholder="限制的数量" v-model.number="form.opportunity_everyday">
                  </el-input>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-col class="col-bottom col-top">
        <h3 style="display: inline;">黑名单</h3>
        <el-popover placement="top-start" trigger="hover" content="点击头像可以删除，添加黑名单成员同时会替换原有数据。">
          <el-button type="text" icon="el-icon-info" slot="reference"></el-button>
        </el-popover>
      </el-col>
      <el-col class="col-top">
        <ul>
          <li style="float:left; margin: 5px 10px;" v-for="user in balckUsers" :key="user.id" @click="removeUser(user)">
            <img v-if="user.portrait" :src="user.portrait" class="avatars">
            <i v-else class="iconfont ali-avatar"></i>
            <div class="black-name">{{user.user_name}}</div>
          </li>
        </ul>
        <i class="iconfont ali-tianjia" style="float:left; margin: 5px 10px;" @click="openUserTemp"></i>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" style="margin: 50px 0">
      <el-col :span="2">
        <el-button type="primary" style="width: 100%" @click="validate">保存</el-button>
      </el-col>
    </el-row>
    <!-- 部门人员获取 -->
    <section>
      <memberTemp ref="childInit" @saveUsers="saveUsers" @closeTransfer="isShow.transfer = false" :isShow="isShow.transfer"></memberTemp>
    </section>
    <!-- 百分比 -->
    <section>
      <percentTemp></percentTemp>
    </section>
    <section>
      <size-temp ref="size" :img.sync="form.file_path" title="图片设置"></size-temp>
    </section>
  </div>
</template>
<script>
import createTemp from './../components/createTemp'
import percentTemp from './../components/percent'
import member_transfer from '@/views/addressbook/components/add_member_transfer'
import { mapGetters } from 'vuex'
import { formateBool } from '@/utils'
import { draw_save, draw_edit } from '@/api/draw'
import sizeTemp from '@/components/draggableSize'

export default {
  components:{ 'rowTemp': createTemp , 'memberTemp': member_transfer, percentTemp, sizeTemp},
  name: 'create',
  data(){
    return {
      form: {file_path: '',opportunity_everyday: 0,opportunity_everyone: 0, drawItems: []},
      isShow: {transfer: false ,everyday_status: 0, everyone_status: 0},
      tempNames: ['一','二','三','四','五','六','七','八'],
      veri: {rowTemp: true, form: true},
      balckUsers: [],
      ossPublicUrl: localStorage.getItem("ossPublicUrl"),
      loading: false
    }
  },
  computed:{
    ...mapGetters([
        'percent','cacheForm','checkDraw'
    ])
  },
  methods: {
    sizeSet(){
      this.$refs.size.open()
    },
    judge(e){//用来判断子集里面是否可以继续往下执行
      this.veri.rowTemp = e;
    },
    openUserTemp(){//打开通讯录面板
      this.isShow.transfer = true;
      this.$refs.childInit.openTransfer();
    },
    saveUsers(users){//保存小组用户
      this.balckUsers = users;
      this.isShow.transfer = false;
    },
    removeUser(e){
      let key = this.balckUsers.indexOf(e);
      this.balckUsers.splice(key, 1);
    },
    async rowTempValidate(){//rowTemp校验
      this.veri.rowTemp = true;
      this.form.drawItems = [];
      for (let j = 0; j < 8; j++) {
        this.$refs.childValidate[j].validate();
        this.form.drawItems[j] = this.$refs.childValidate[j].form;
      }
    },
    async submitRowTemp(){
      await this.rowTempValidate();
      if(!this.veri.rowTemp){//rowTemp 必须全部校验通过
        return false;
      }
      if(this.percent != 100){
        this.$message.error("请确认中奖概率");
        return false;
      }
      return true;
    },
    async formValidate(){//本表单全部验证
      this.veri.form = true;
      for (let i = 1; i < 6; i++) {
        this.$refs[`form${i}`].validate((valid) => {
          if (!valid) {
            this.veri.form = false
            return false;
          }
        });
      }
    },
    beforeAvatarUpload(file) {
      let name = file.name.split(".");
      if (name[name.length - 1] === "jpg" || name[name.length - 1] === "jpeg" || name[name.length - 1] === "png" ) {
        return file;
      } else {
        this.$message.error("图片只能是 jpeg/png 格式!");
        return false;
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.file_path = this.ossPublicUrl + "/" + res.data.file_path;
    },
    async validate(){
      let flag = await this.submitRowTemp();
      if(!flag) return;
      await this.formValidate();
      if(!this.veri.form) return;
      this.form.everyday_status = formateBool(this.form.everyday);
      this.form.everyone_status = formateBool(this.form.everyone);
      this.form.active_starttime = this.checkDraw == 'edit' ? this.form.date[0] : this.form.date[0] + ' 00:00:00'
      this.form.active_endtime = this.checkDraw == 'edit' ? this.form.date[1] : this.form.date[1] + ' 23:59:59'
      let drawBlacklists = []
      for (let i = 0; i < this.balckUsers.length; i++) { //格式化黑名单数据
        let element = this.balckUsers[i];
        // this.$set(element,'user_id', element.user_id || element.id.substring(7,element.id.length))
        // let id = element.user_id;
        let id = this.checkDraw == 'edit' ? element.user_id || element.id.substring(7,element.id.length) : element.user_id || element.id.substring(7,element.id.length);
        drawBlacklists.push({
          user_id: id
        })
      }
      this.form.drawBlacklists = JSON.stringify(drawBlacklists);
      this.form.drawItems = JSON.stringify(this.form.drawItems);
      const args = {...this.form, company_id: localStorage.getItem("companyId") - 0}
      if(this.checkDraw == 'edit'){
        this.editObj(args);
      }else{
        this.saveObj(args);
      }
    },
    async editObj(args){//编辑
      this.loading = true;
      const { data } = await draw_edit(args);
      if(data.status == 100){
        this.$message.success("修改成功");
        this.$store.dispatch('ClearDrawFormData');//清空缓存
        this.$router.push("/other/draw");
      }
      this.loading = false;
    },
    async saveObj(args){
      this.loading = true;
      const { data } = await draw_save(args);
      if(data.status == 100){
        this.$message.success("创建成功");
        this.$store.dispatch('ClearDrawFormData');//清空缓存
        this.$router.push("/other/draw");
      }
      this.loading = false;
    },
    editForm(){//初始化编辑
      this.form = this.cacheForm;
      this.balckUsers = this.cacheForm.drawBlacklists;
    }
  },
  created(){
    if(this.checkDraw == 'edit'){
      this.editForm();//初始化编辑
    }
  }
  
}
</script>
<style lang="scss" scoped>
$border: 1px dashed #d9d9d9;
$picture-size: 120px;
$color: #606266;
.app-container{
  padding: 40px;
}
.col-bottom{
  border-bottom: 1px solid #E5E5E5; 
  padding-bottom: 10px;
}
.col-top{
  margin-top: 15px;
}
.col-temp{
  border-bottom: 1px solid #E5E5E5; 
  margin: 8px 0;
}
.iconfont{
  font-size: 40px;
  color: #C6C5C5;
  &:hover{
    cursor: pointer;
  }
}
.avatars{
  width: 40px;
  border-radius: 50%;
}
.black-name{
  font-size: 13px;
  color: #3A3A3A;
  text-align: center;
}
.avatar-uploader {
  .el-upload {
    border: $border;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  border: $border;
  font-size: 28px;
  color: #8c939d;
  width: $picture-size;
  height: $picture-size;
  line-height: $picture-size;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
}
.avatar {
  width: 60%;
  display: block;
  border-radius: 5px;
  cursor: pointer;
}
</style>
